using System;
using System.Html;
using System.Runtime.CompilerServices;

namespace Nsb
{
    public delegate void AnonymousMethod();
    public delegate bool AnonymousBoolMethod();

    [IgnoreNamespace]
    public static class Sleep
    {
        private const int MaxWaitTime = 40000;

        public static void Delay(AnonymousMethod fn, int ms)
        {
            Window.SetTimeout(fn, ms);
        }

        public static void DoNow(AnonymousMethod fn, int ms)
        {
            fn();
        }

        public static void ThrowDelay(AnonymousMethod fn, int ms)
        {
            Window.SetTimeout(fn, ms);
            throw new Exception("Delay finish throw out");
        }

        [AlternateSignature]
        public static extern void Wait(AnonymousMethod fn, AnonymousBoolMethod condition);

        public static void Wait(AnonymousMethod fn, AnonymousBoolMethod condition, int startTime)
        {
            if (condition())
            {
                fn();
                return;
            }

            if (Script.IsNullOrUndefined(startTime))
                startTime = (new Date()).GetTime();

            if ((new Date()).GetTime() - startTime > MaxWaitTime)
                throw new Exception("Max wait time exceeded");

            Window.SetTimeout(
                delegate
                    {
                        Wait(fn, condition, startTime);
                    }, 13);
        }
    }
}
